/*
 * @Author       : 魏威 <1209562577@qq.com>
 * @Date         : 2022-02-22 17:14 周2
 * @Description  : 注册页
 */

import { Form, Input } from "antd";
import { BigButton } from "components/lib";
import { useAuth } from "context/auth-context";
import { useAsync } from "hooks/useAsync";
import React from "react";

export default function RegisterScreen({
  onError,
}: {
  onError: (error: Error) => void;
}) {
  const { register } = useAuth();
  const { run, isLoading } = useAsync(undefined, { throwOnError: true });

  const handleSubmit = async ({
    cpassword,
    ...values
  }: {
    username: string;
    password: string;
    cpassword: string;
  }) => {
    try {
      await run(register(values));
    } catch (error) {
      onError(error as Error);
    }
  };

  return (
    <div>
      <Form onFinish={handleSubmit}>
        <Form.Item
          name={"username"}
          rules={[{ required: true, message: "请输入用户名" }]}
        >
          <Input placeholder={"用户名"} type={"text"} />
        </Form.Item>
        <Form.Item
          name={"password"}
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input placeholder={"密码"} type={"text"} />
        </Form.Item>
        <Form.Item
          name={"cpassword"}
          rules={[{ required: true, message: "请输入确认密码" }]}
        >
          <Input placeholder={"确认密码"} type={"text"} />
        </Form.Item>
        <Form.Item>
          <BigButton loading={isLoading} type={"primary"} htmlType={"submit"}>
            注册
          </BigButton>
        </Form.Item>
      </Form>
    </div>
  );
}
